/*
 * Copyright (c) 2018-2024 北京华恒盛世科技有限公司
 * QUICKPOOL is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *     http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
*/

#include <string.h>
#include <malloc.h>
#include <pwd.h>

#include "common.h"

int
addmore_admins(char *word, struct admins *admins, unsigned int *numAds)
{
    struct passwd *pw;
    char **tempNames;
    unsigned int i;
    uid_t *tempGids;
    uid_t *tempIds;

    pw = get_user_byname(word);
    if (NULL == pw) {
        log_message(ERR, NOCLASS, "%s: <%s> is not a valid user name; ignored", __func__, word);
        return 0;
    }

    if (is_admin(admins->admin_names, pw->pw_name, admins->num_admins)) {
        log_message(WARNING, NOCLASS, "%s: Duplicate user name <%s> %s; ignored",
                    __func__, word);
        return 0;
    }

    admins->admin_ids[admins->num_admins] = pw->pw_uid;
    admins->admin_gids[admins->num_admins] = pw->pw_gid;
    admins->admin_names[admins->num_admins] = copy_string(pw->pw_name);
    admins->num_admins += 1;

    log_message(DEBUG2, TRACER, "%s: uid %d gid %d name <%s>",
                __func__, pw->pw_uid, pw->pw_gid, pw->pw_name);

    if (admins->num_admins >= *numAds) {
        *numAds = *numAds * 2;
        tempIds = (uid_t *)realloc(admins->admin_ids, *numAds * sizeof(uid_t));
        tempGids = (uid_t *)realloc(admins->admin_gids, *numAds * sizeof(uid_t));
        tempNames = (char **)realloc(admins->admin_names, *numAds * sizeof(char *));
        if (tempIds == NULL || tempGids == NULL || tempNames == NULL) {

            log_message(ERR, NOCLASS, "%s: realloc(%d) failed: %m",
                        __func__, *numAds*sizeof(char *)*3);
            FREEUP (tempIds);
            FREEUP (tempGids);
            FREEUP (tempNames);

            FREEUP (admins->admin_ids);
            FREEUP (admins->admin_gids);
            for (i = 0; i < admins->num_admins; i++)
                FREEUP (admins->admin_names[i]);
            FREEUP (admins->admin_names);
            admins->num_admins = 0;
            return -1;
        } else {
            admins->admin_ids = tempIds;
            admins->admin_gids = tempGids;
            admins->admin_names = tempNames;
        }
    }
    return 0;
}

int
is_admin(char **adminNames, char *userName, int actAds)
{
    int i;

    if (actAds == 0)
        return FALSE;

    for (i = 0; i < actAds; i++) {
        if (strcmp (adminNames[i], userName) == 0)
            return TRUE;
    }

    return FALSE;
}

